package sort;

public class QuickSort {
    public void sort(int[] nums) {
        quickSort(nums, 0, nums.length - 1);
    }

    private void quickSort(int[] nums, int left, int right) {
        if (left >= right) return;
        int partitionIdx = partition(nums, left, right);
        quickSort(nums, left, partitionIdx - 1);
        quickSort(nums, partitionIdx + 1, right);
    }

    private int partition(int[] nums, int left, int right) {
        int pivot = left; // 这里基准值取的是分区最左边的元素
        int index = pivot + 1;
        for (int i = index; i <= right; ++i) {
            if (nums[i] < nums[pivot]) {
                swap(nums, i, index);
                index++;
            }
        }
        swap(nums, index - 1, pivot);
        return index - 1;
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public static void main(String[] args) {
        int[] nums = {1, 0, 2, 4, 8, 5, 6, 7, 3, 9};
        QuickSort solution = new QuickSort();
        Common.printArray(nums);
        solution.sort(nums);
        Common.printArray(nums);
    }
}
